import { put } from 'redux-saga/effects';
import { createReducer } from './reducers/utils';

const START = '@@REDUX_SAGA_LOADING/START';
const STOP = '@@REDUX_SAGA_LOADING/STOP';
const START_ALL = '@@REDUX_SAGA_LOADING/START_ALL';
const STOP_ALL = '@@REDUX_SAGA_LOADING/STOP_ALL';

function createReduxSagaLoading() {
  const initialState = {};
  const reduxReducers = {
    [START](state, action) {
      const { modelNames } = action;
      const startModels = {};
      for (const name of modelNames) {
        startModels[name] = true;
      }
      return {
        ...state,
        ...startModels,
      };
    },
    [STOP](state, action) {
      const { modelNames } = action;
      const startModels = {};
      for (const name of modelNames) {
        startModels[name] = false;
      }
      return {
        ...state,
        ...startModels,
      };
    },
    [START_ALL](state) {
      const starts = Object.keys(state).reduce((obj, key) => {
        obj[key] = true;
        return obj;
      }, {});
      return starts;
    },
    [STOP_ALL](state) {
      const stops = Object.keys(state).reduce((obj, key) => {
        obj[key] = false;
        return obj;
      }, {});
      return stops;
    },
  };
  return createReducer(reduxReducers, initialState);
}

function* startLoading(...modelNames) {
  yield put({
    type: START,
    modelNames,
  });
}

function* stopLoading(...modelNames) {
  yield put({
    type: STOP,
    modelNames,
  });
}
function* startAllLoading() {
  yield put({
    type: START_ALL,
  });
}

function* stopAllLoading() {
  yield put({
    type: STOP_ALL,
  });
}

export {
  createReduxSagaLoading,
  startLoading,
  stopLoading,
  startAllLoading,
  stopAllLoading,
};
